//
//  56. 合并区间.swift
//  Top600
//
//  Created by rjb on 2021/7/28.
//

import Foundation
class Solution56 {
    func merge(_ intervals: [[Int]]) -> [[Int]] {
        guard intervals.count > 0 else {
            return intervals
        }
        let intervals = intervals.sorted { first, second in
            return first.first! < second.first!
        }
        var result:[[Int]] = []
        var pre: [Int]?  // [1,4], [2,3]
        for item in intervals {
            if let realPre = pre {
                let preFirst: Int = realPre.first!
                let preLast: Int = realPre.last!
                let itemFirst: Int = item.first!
                let itemLast = item.last!
                // 这里要非常注意
                if preLast >= itemFirst {
                    pre = [min(preFirst, itemFirst), max(itemLast, preLast) ]
                } else {
                    result.append(realPre)
                    pre = item
                }
            } else {
                pre = item
            }
        }
        if let realPre = pre {
            result.append(realPre)
        }
        return result
    }
    
    static func test() {
        let solution = Solution56()
        let intervals = [[1,4], [2,3]]
        let result = solution.merge(intervals)
        print(result)
    }
}
